//
//  LoginViewController.m
//  Light
//
//  Created by 骁唐 on 15/8/20.
//  Copyright (c) 2015年 骁唐. All rights reserved.
//

#import "LoginViewController.h"
#import "SliderViewController.h"
#import "UserViewController.h"
#import "HomeTwoViewController.h"
#import "AFNetworking.h"
#import "NetworkTool.h"
#import "constantDefinition.h"
#import "assessment.h"
#import "UserConfig.h"
#import "MBProgressHUD.h"
#import "ViewController.h"

#import "UMSocialSnsPlatformManager.h"
#import "UMSocialAccountManager.h"
#import "NameViewController.h"
@interface LoginViewController ()<UIGestureRecognizerDelegate,UITextFieldDelegate,MBProgressHUDDelegate>
@property (weak, nonatomic) IBOutlet UITextField *phoneText;
@property (weak, nonatomic) IBOutlet UITextField *passWordText;
@property (weak, nonatomic) IBOutlet UIView *myView;
@property (weak, nonatomic) IBOutlet UIImageView *backGround;
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.phoneText.keyboardType = UIKeyboardTypeNumberPad;
    self.phoneText.delegate = self;
    self.passWordText.delegate = self;
    self.passWordText.returnKeyType = UIReturnKeyDone;
    self.phoneText.textColor = [UIColor whiteColor];
    [self.passWordText resignFirstResponder];
    
    //等待菊花
    MBProgressHUD *progressView = [[MBProgressHUD alloc]initWithView:self.view];
    progressView.delegate       = self;
    progressView.labelText      = @"";
    self.mbProgressHud       = progressView;
    [self.view addSubview:progressView];
    [_mbProgressHud show:YES];
    self.mbProgressHud.hidden = YES;
    
    
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidAppear:(BOOL)animated {
    //禁用滑动手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
#pragma mark-
#pragma mark 点击空白处，键盘回收
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.phoneText resignFirstResponder];
    [self.passWordText resignFirstResponder];
}
#pragma mark-
#pragma mark 键盘return按钮处理优化
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];//隐藏键盘
    if (textField == self.passWordText)
    {//密码   OK按钮就应该直接调起登陆
        [self loadLogin];//调起登陆
    }
    return YES;
}
#pragma mark-
#pragma mark 限制手机号码11位输入
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == self.phoneText)
    {//手机限制11位输入
        if (range.location==11)
        {
            //            [self.phoneTF resignFirstResponder];
            textField.text=[textField.text substringToIndex:10];
            return YES;
        }
    }
    return YES;
}

#pragma mark -
#pragma mark 登陆Click
- (IBAction)loginClick {
    
    
    //
    //    HomeTwoViewController *homet = [[HomeTwoViewController alloc] init];
    //    SliderViewController *slider = [SliderViewController sharedSliderController];
    //    slider.LeftSContentOffset =  SCREEN_WIDTH - 40;
    //    slider.LeftSContentScale = 1;
    //
    //    UIStoryboard *userSt = [UIStoryboard storyboardWithName:@"User" bundle:nil];
    //    slider.LeftVC = [userSt instantiateViewControllerWithIdentifier:@"userViewId"];
    //
    //    slider.MainVC = homet;
    //
    //    [self.navigationController pushViewController:slider animated:YES];
    //
    
    [self loadLogin];//调起登陆
}

#pragma mark -
#pragma mark 调起网络请求登陆
- (void)loadLogin
{
    [self.view endEditing:YES];
    //第一步:需要先判断手机号码格式，第二判断密码是否为空
    if (![TJJDefines isMobile:self.phoneText.text])
    {//手机号码格式错误
        TJJALERT_VIEW(ERROR_MOBILEINFO);
    }
    else
    {
        if (self.passWordText.text.length == 0)
        {//密码为0
            TJJALERT_VIEW(@"密码不能为空！");
        }
        else
        {//密码不为空，提交网络请求
            self.mbProgressHud.hidden = NO;
            [_phoneText resignFirstResponder];
            [_passWordText resignFirstResponder];
            //    _phoneText.text = @"15505188017";
            //    _passWordText.text = @"1234567";
            if ([NetworkTool isMobileNumber:_phoneText.text]) {
                //传的参数
                NSDictionary *dic= @{@"cellPhone":self.phoneText.text,@"password":self.passWordText.text};
                __weak LoginViewController *weakSelf = self;
                AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
                httpManager.requestSerializer = [[AFHTTPRequestSerializer alloc]init];
                httpManager.responseSerializer = [[AFHTTPResponseSerializer alloc]init];
                //地址
                [httpManager POST:Login parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
                    
                    NSDictionary *retDic = [NetworkTool toNSDictionary:responseObject];
                    
                    if ([retDic[@"a"] intValue] == 1) {
                        
                        //保存token
                        UserConfig *userConfig = [UserConfig sharingUserConfig];
                        [userConfig setToken:retDic[@"b"]];
                        [userConfig setCurrentPhoneNum:weakSelf.phoneText.text];
                        [userConfig setCurrentUserPsd:weakSelf.passWordText.text];
                        [userConfig setHaveLogin:@"login"];
                        if (self.quit == YES) {
                            for (UIViewController *controller in self.navigationController.viewControllers) {
                                if ([controller isKindOfClass:[SliderViewController class]]) {
                                    [self.navigationController popToViewController:controller animated:YES];
                                }
                            }
                        }else
                        {
                            BOOL HaveRoot = NO;//标记是否有Root
                            for (UIViewController * controller in self.navigationController.viewControllers)
                            {
                                if ([controller isKindOfClass:[SliderViewController class]])
                                {//如果是rootView
                                    HaveRoot = YES;
                                    [self.navigationController popToViewController:controller animated:YES];
                                }
                            }
                            if (!HaveRoot)
                            {
                                HomeTwoViewController *homet = [[HomeTwoViewController alloc] init];
                                SliderViewController *slider = [SliderViewController sharedSliderController];
                                    if (SCREEN_WIDTH > 320)
                                    {
                                        slider.LeftSContentOffset =  SCREEN_WIDTH-WIDTH_MAIN_6*SCREEN_SCALE;//SXW__设置侧边栏
                                    }
                                    else
                                    {
                                        slider.LeftSContentOffset =  SCREEN_WIDTH-WIDTH_MAIN*SCREEN_SCALE;//SXW__设置侧边栏
                                    }                            slider.LeftSContentScale = 1;//左视图缩小，1表示不缩小。
                                
                                UIStoryboard *userSt = [UIStoryboard storyboardWithName:@"User" bundle:nil];
                                slider.LeftVC = [userSt instantiateViewControllerWithIdentifier:@"userViewId"];
                                slider.MainVC = homet;
                                AppDelegate * delegate = [[UIApplication sharedApplication] delegate];
                                UINavigationController *navigationVc = [[UINavigationController alloc]initWithRootViewController:slider];
                                navigationVc.navigationBar.hidden = YES;
                                delegate.window.rootViewController = navigationVc;
                            }
                        }
                    }else if ([retDic[@"a"] intValue] == 0) {
                        TJJALERT_VIEW(@"账号或密码错误");
                    }
                    _mbProgressHud.hidden = YES;
                    
                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                    TJJALERT_VIEW(@"网络连接错误");
                    _mbProgressHud.hidden = YES;
                }];
            }else {
                TJJALERT_VIEW(@"请输入正确地手机号");
                _mbProgressHud.hidden = YES;
            }
        }
    }
}

//暂时未使用
- (void) test
{
    UIStoryboard *HomeStoryboard = [UIStoryboard storyboardWithName:@"Home" bundle:nil];
    [self.navigationController pushViewController:[HomeStoryboard instantiateViewControllerWithIdentifier:@"homeViewId"] animated:YES];
}

#pragma mark -
#pragma mark 忘记密码按钮
- (IBAction)noPassWordClick {
    [self.view endEditing:YES];
    [self performSegueWithIdentifier:@"loginToPassWord" sender:nil];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //强制竖屏
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:
                                        UIInterfaceOrientationPortrait]  forKey:@"orientation"];
    //SXW__标记，设置背景
    long long int currentTimeInt = [TJJDefines getTimeIntSince1970Current];
    if (currentTimeInt>=16200&& currentTimeInt <=34200) {
        self.backGround.image = [UIImage imageNamed:@"backgroundOne"];
    }else if (currentTimeInt>34200 && currentTimeInt<=55800)
    {
        self.backGround.image = [UIImage imageNamed:@"backgroundTwo"];
    }else if (currentTimeInt>55800 && currentTimeInt<=70200)
    {
        self.backGround.image = [UIImage imageNamed:@"backgroundThree"];
    }else if(currentTimeInt >70200 || currentTimeInt<16200)
    {
        self.backGround.image = [UIImage imageNamed:@"background_night"];
    }
}

#pragma mark -
#pragma mark 点击微信登录响应返回
- (IBAction)weixinClick {
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToWechatSession];
    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary]valueForKey:UMShareToWechatSession];
            TJJLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
            NSDictionary *dic= @{@"uid":snsAccount.usid};
            AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
            httpManager.requestSerializer = [[AFHTTPRequestSerializer alloc] init];
            httpManager.responseSerializer = [[AFHTTPResponseSerializer alloc] init];
            //地址
            [httpManager POST:URL_REGIST_ANOTHER parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
                UserConfig *config = [UserConfig sharingUserConfig];
                NSDictionary *retDic = [NetworkTool toNSDictionary:responseObject];
//                __weak LoginViewController *weakSelf = self;
                if ([retDic[@"a"] intValue] == 1)
                {
                    TJJLog(@"111111111111");
                    [config setToken:retDic[@"b"]];
                    if ([retDic[@"c"] intValue] == 1)
                    {
                        if (self.quit == YES) {
                            for (UIViewController *controller in self.navigationController.viewControllers) {
                                if ([controller isKindOfClass:[SliderViewController class]]) {
                                    [self.navigationController popToViewController:controller animated:YES];
                                }
                            }
                        }else{
                            BOOL HaveRoot = NO;//标记是否有Root
                            for (UIViewController * controller in self.navigationController.viewControllers)
                            {
                                if ([controller isKindOfClass:[SliderViewController class]])
                                {//如果是rootView
                                    HaveRoot = YES;
                                    [self.navigationController popToViewController:controller animated:YES];
                                }
                            }
                            if (!HaveRoot)
                            {
                                HomeTwoViewController *homet = [[HomeTwoViewController alloc] init];
                                SliderViewController *slider = [SliderViewController sharedSliderController];
                                [config setHaveLogin:@"login"];
                                if (SCREEN_WIDTH > 320)
                                {
                                    slider.LeftSContentOffset =  SCREEN_WIDTH-WIDTH_MAIN_6*SCREEN_SCALE;//SXW__设置侧边栏
                                }
                                else
                                {
                                    slider.LeftSContentOffset =  SCREEN_WIDTH-WIDTH_MAIN*SCREEN_SCALE;//SXW__设置侧边栏
                                }
                                slider.LeftSContentScale = 1;//左视图缩小，1表示不缩小。
                                UIStoryboard *userSt = [UIStoryboard storyboardWithName:@"User" bundle:nil];
                                slider.LeftVC = [userSt instantiateViewControllerWithIdentifier:@"userViewId"];
                                slider.MainVC = homet;
                                AppDelegate * delegate = [[UIApplication sharedApplication] delegate];
                                UINavigationController *navigationVc = [[UINavigationController alloc]initWithRootViewController:slider];
                                navigationVc.navigationBar.hidden = YES;
                                delegate.window.rootViewController = navigationVc;
                            }
                            //    [self.navigationController pushViewController:slider animated:YES];
//                            [weakSelf.navigationController pushViewController:slider animated:YES];
                        }
                    }else if ([retDic[@"c"] intValue] == 0)
                    {
                          [self performSegueWithIdentifier:@"loginToName" sender:nil];
                    }
                    
                }else if ([retDic[@"a"] intValue] == 0) {
                    TJJLog(@"00000000000");
                    
                }else if([retDic[@"a"] intValue] == -1){
                    TJJLog(@"-11111111");
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                TJJLog(@"shibai ");
                TJJALERT_VIEW(@"网络连接错误");
                _mbProgressHud.hidden = YES;
            }];
        }
    });
}

#pragma mark -
#pragma mark 点击微博登录响应返回
- (IBAction)weiboClick:(UIButton *)sender {
//    self.mbProgressHud.hidden = NO;
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
    UserConfig *config = [UserConfig sharingUserConfig];
    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        //获取微博用户名、uid、token等
        if (response.responseCode == UMSResponseCodeSuccess) {
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToSina];
            TJJLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
            //传的参数
            NSDictionary *dic= @{@"uid":snsAccount.usid};
            AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
            httpManager.requestSerializer = [[AFHTTPRequestSerializer alloc] init];
            httpManager.responseSerializer = [[AFHTTPResponseSerializer alloc] init];
            //地址
            [httpManager POST:URL_REGIST_ANOTHER parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSDictionary *retDic = [NetworkTool toNSDictionary:responseObject];
                __weak LoginViewController *weakSelf = self;
                if ([retDic[@"a"] intValue] == 1)
                {
                    TJJLog(@"111111111111");
                    [config setToken:retDic[@"b"]];
                    if ([retDic[@"c"] intValue] == 1)
                    {
                        if (weakSelf.quit == YES)
                        {
                            for (UIViewController *controller in self.navigationController.viewControllers)
                            {
                                if ([controller isKindOfClass:[SliderViewController class]])
                                {
                                    [self.navigationController popToViewController:controller animated:YES];
                                }
                            }
                        }
                        else
                        {
                            BOOL HaveRoot = NO;//标记是否有Root
                            for (UIViewController * controller in self.navigationController.viewControllers)
                            {
                                if ([controller isKindOfClass:[SliderViewController class]])
                                {//如果是rootView
                                    HaveRoot = YES;
                                    [self.navigationController popToViewController:controller animated:YES];
                                }
                            }
                            if (!HaveRoot)
                            {
                                HomeTwoViewController *homet = [[HomeTwoViewController alloc] init];
                                SliderViewController *slider = [SliderViewController sharedSliderController];
                                [config setHaveLogin:@"login"];
                                
                                if (SCREEN_WIDTH > 320)
                                {
                                    slider.LeftSContentOffset =  SCREEN_WIDTH-WIDTH_MAIN_6*SCREEN_SCALE;//SXW__设置侧边栏
                                }
                                else
                                {
                                    slider.LeftSContentOffset =  SCREEN_WIDTH-WIDTH_MAIN*SCREEN_SCALE;//SXW__设置侧边栏
                                }
                                slider.LeftSContentScale = 1;//左视图缩小，1表示不缩小。
                                UIStoryboard *userSt = [UIStoryboard storyboardWithName:@"User" bundle:nil];
                                slider.LeftVC = [userSt instantiateViewControllerWithIdentifier:@"userViewId"];
                                slider.MainVC = homet;
                                AppDelegate * delegate = [[UIApplication sharedApplication] delegate];
                                UINavigationController *navigationVc = [[UINavigationController alloc]initWithRootViewController:slider];
                                navigationVc.navigationBar.hidden = YES;
                                delegate.window.rootViewController = navigationVc;
                            }
                        }
                    }else if ([retDic[@"c"] intValue] == 0)
                    {
                        [self performSegueWithIdentifier:@"loginToName" sender:nil];
                    }
                    
                }else if ([retDic[@"a"] intValue] == 0)
                {
                    TJJLog(@"00000000000");
                    
                }else if([retDic[@"a"] intValue] == -1)
                {
                    TJJLog(@"-11111111");
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                TJJLog(@"shibai ");
                TJJALERT_VIEW(@"网络连接错误");
                _mbProgressHud.hidden = YES;
            }];
        }});
}

#pragma mark -
#pragma mark 点击QQ登录响应返回
- (IBAction)qqClick {
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToQQ];
    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        //          获取微博用户名、uid、token等
        if (response.responseCode == UMSResponseCodeSuccess) {
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToQQ];
            TJJLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
            NSDictionary *dic= @{@"uid":snsAccount.usid};
            AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
            httpManager.requestSerializer = [[AFHTTPRequestSerializer alloc] init];
            httpManager.responseSerializer = [[AFHTTPResponseSerializer alloc] init];
            //地址
            [httpManager POST:URL_REGIST_ANOTHER parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
                UserConfig *config = [UserConfig sharingUserConfig];
                NSDictionary *retDic = [NetworkTool toNSDictionary:responseObject];
                __weak LoginViewController *weakSelf = self;
                if ([retDic[@"a"] intValue] == 1)
                {
                    [config setToken:retDic[@"b"]];
                    if ([retDic[@"c"] intValue] == 1)
                    {
                        if (weakSelf.quit == YES)
                        {
                            for (UIViewController *controller in self.navigationController.viewControllers)
                            {
                                if ([controller isKindOfClass:[SliderViewController class]])
                                {
                                    [self.navigationController popToViewController:controller animated:YES];
                                }
                            }
                        }
                        else
                        {
                            BOOL HaveRoot = NO;//标记是否有Root
                            for (UIViewController * controller in self.navigationController.viewControllers)
                            {
                                if ([controller isKindOfClass:[SliderViewController class]])
                                {//如果是rootView
                                    HaveRoot = YES;
                                    [self.navigationController popToViewController:controller animated:YES];
                                }
                            }
                            if (!HaveRoot)
                            {
                                HomeTwoViewController *homet = [[HomeTwoViewController alloc] init];
                                SliderViewController *slider = [SliderViewController sharedSliderController];
                                [config setHaveLogin:@"login"];
                                if (SCREEN_WIDTH > 320)
                                {
                                    slider.LeftSContentOffset =  SCREEN_WIDTH-WIDTH_MAIN_6*SCREEN_SCALE;//SXW__设置侧边栏
                                }
                                else
                                {
                                    slider.LeftSContentOffset =  SCREEN_WIDTH-WIDTH_MAIN*SCREEN_SCALE;//SXW__设置侧边栏
                                }
                                slider.LeftSContentScale = 1;//左视图缩小，1表示不缩小。
                                UIStoryboard *userSt = [UIStoryboard storyboardWithName:@"User" bundle:nil];
                                slider.LeftVC = [userSt instantiateViewControllerWithIdentifier:@"userViewId"];
                                slider.MainVC = homet;
                                AppDelegate * delegate = [[UIApplication sharedApplication] delegate];
                                UINavigationController *navigationVc = [[UINavigationController alloc]initWithRootViewController:slider];
                                navigationVc.navigationBar.hidden = YES;
                                delegate.window.rootViewController = navigationVc;
                            }
                        }
                    }
                    else if ([retDic[@"c"] intValue] == 0)
                    {
                        [self performSegueWithIdentifier:@"loginToName" sender:nil];
                    }
                }
                else if ([retDic[@"a"] intValue] == 0)
                {
                    TJJLog(@"00000000000");
                }
                else if([retDic[@"a"] intValue] == -1)
                {
                    TJJLog(@"-11111111");
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                TJJLog(@"shibai ");
                TJJALERT_VIEW(@"网络连接错误");
                _mbProgressHud.hidden = YES;
            }];
        }});
}

@end
